

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;

import com.model.common.PayType;
import com.model.dto.OrderDto;
import com.model.dto.PayDto;
import com.model.dto.TicketDto;

public class OrderTestSpring {
	private static final String SECRET_360 = "3baff651dba1988538f6fd73f6f5a9e6";
	private static final String SECRET_TEST = "4ec7f9d284e74d79f9c5b9bc441e8bc7";
	private static final ObjectMapper objectMapper = new ObjectMapper();
	
	@Before
	public void setUp() {
		objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
	}
	
	public String getSign(String body, String headers, String secret) {
		String head = getCodeString(headers.split(";"));
		return MD5.code((secret + head + body + secret).toLowerCase());
	}
	
	private String getCodeString(String[] headers) {
		Map<String, String> map = new HashMap<String, String>();
		for (String s : headers) {
			String[] ss = s.split("=");
			map.put(ss[0], ss[1]);
		}
		List<String> list = new ArrayList<String>(map.keySet());
		Collections.sort(list);
		
		StringBuilder sb = new StringBuilder();
		for (String s : list) {
			sb.append(s).append(map.get(s));
		}
		return sb.toString();
	}
	
	private void sendPost(String agent, String secret, String path, Object data) {
		HttpClient httpClient = new DefaultHttpClient();
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("version=1.0;").append("agent=").append(agent).append(";timestamp=");
			sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
			
			String body = readBody(data);
			String sign = getSign(body, sb.toString(), secret);
			HttpPost httpPost = new HttpPost("http://localhost:8035/webapi" + path);
			HttpEntity httpEntity = new StringEntity(body, MediaType.APPLICATION_JSON_VALUE ,HTTP.UTF_8);
	        httpPost.setEntity(httpEntity);
			httpPost.addHeader(HttpHeaders.CONTENT_ENCODING, "UTF-8");
			sb.append(";sign=").append(sign);
			httpPost.addHeader("Content-Signature", sb.toString());
			
			outPutResult(httpClient, httpPost);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}
	
	private String readBody(Object data) {
		try {
			return objectMapper.writeValueAsString(data);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void outPutResult(HttpClient httpClient, HttpPost httpPost)
		throws IOException, ClientProtocolException {
		
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		System.out.println("----------------------------------------");
		System.out.println("status = " + response.getStatusLine().getStatusCode());
		System.out.println("type = " + entity.getContentType());
		System.out.println("content = " + EntityUtils.toString(entity));
		System.out.println("----------------------------------------");
	}
	
	@Test
	public void orderQuery360() throws UnsupportedEncodingException {
		String agent = "0063001";
		String path = "/order/view";
		String[] cds = new String[]{"F1337158708811", "F1336964081746"};
		sendPost(agent, SECRET_360, path, cds);
	}
	
	@Test
	public void orderQueryTest() throws UnsupportedEncodingException {
		String agent = "0027001";
		String path = "/mango/order/query.json";
		String[] cds = new String[]{"F1337158708811", "F1336964081746"};
		sendPost(agent, SECRET_TEST, path, cds);
	}
	
	@Test
	public void orderBook360() throws UnsupportedEncodingException {
		String agent = "0063001";
		String path = "/mango/order/book.json";
		OrderDto dto = bulidOrderDto();
		sendPost(agent, SECRET_360, path, dto);
	}
	
	@Test
	public void orderBookTest() throws UnsupportedEncodingException {
		String agent = "0027001";
		String path = "/mango/order/book.json";
		OrderDto dto = bulidOrderDto();
		sendPost(agent, SECRET_TEST, path, dto);
	}
	
	public OrderDto bulidOrderDto() {
		OrderDto order = new OrderDto();
		order.setAgentCode("0063001");

		PayDto pay = new PayDto();
		pay.setAmount(220d);
		pay.setType(PayType.Online);
		
		List<TicketDto> tickets = new ArrayList<TicketDto>();
		TicketDto ticket = new TicketDto();
		ticket.setName("Leo");
		ticket.setPrice(110d);
		tickets.add(ticket);
		
		ticket = new TicketDto();
		ticket.setName("Anny");
		ticket.setPrice(110d);
		tickets.add(ticket);
		
		order.setPay(pay);
		order.setTickets(tickets);
		
		return order;
	}
	
	@Test
	public void checkTimeSeperate() {
    	Calendar ago = Calendar.getInstance();
    	ago.set(Calendar.MINUTE, ago.get(Calendar.MINUTE) - 3);
    	System.out.println(ago.get(Calendar.MINUTE));
    	Calendar after = Calendar.getInstance();
    	after.set(Calendar.MINUTE, after.get(Calendar.MINUTE) + 3);
    	System.out.println(after.get(Calendar.MINUTE));
//    	if (stamp.before(ago) || stamp.after(after)) {
//    		throw new IllegalArgumentException(String.format(ErrorCode.System.S10006, s));
//    	}
    }
	
	@Test
    public void testStringPost() {
		HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpPost httpPost = new HttpPost("http://localhost:8035/webapi/order/test");
            httpPost.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE);
            
            HttpEntity httpEntity = new StringEntity("F1337158708811测试est", HTTP.UTF_8);
            httpPost.setEntity(httpEntity);
            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            
            String responseBody = httpClient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            System.out.println("----------------------------------------");
            
        } catch (Exception e) {
        } finally {
        	httpClient.getConnectionManager().shutdown();
        }
    }
}

